package com.hw.paltfrom.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.DigestUtils;

//云通讯的发生短信工具
public class SendMessageUtil {

	// 将短信内容按照第三方规定格式化
	private static String formatVcodeContent(String vcode) {
		// 被转码后的content
		String result = "";
		String content = "【贝甜副业】验证码" + vcode + "，用于账号注册，5分钟内有效。验证码提供给他人可能导致帐号被盗，请勿泄露，谨防被骗";
		int index = content.indexOf("?");
		result = content.substring(0, index + 1);
		String temp = content.substring(index + 1);
		try {
			// URLEncode转码会将& ： / = 等一些特殊字符转码,(但是这个字符 只有在作为参数值
			// 时需要转码;例如url中的&具有参数连接的作用，此时就不能被转码)
			String encode = URLEncoder.encode(temp, "gb2312");
			encode = encode.replace("%3D", "=");
			encode = encode.replace("%2F", "/");
			encode = encode.replace("+", "%20");
			encode = encode.replace("%26", "&");
			result += encode;
			return result;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}

	}

	// 发生验证码
	public static boolean sendVerificationCode(String phone) {
		try {
			// 生成随机4位数
			String vCode = RandomStringUtils.random(4, "1234567890");

			// 格式化短信内容
			String content = formatVcodeContent(vCode);

			// 获取当前时间，并按照第三方平台做处理
			DateTimeFormatter DATETIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			String now = LocalDateTime.now().format(DATETIME);

//			String str = "c898930" + now;
			String str = OverParameterUtil.password + now;
			String password = DigestUtils.md5DigestAsHex(str.getBytes());
			String timestamp = now.replaceAll(" ", "%20");

			StringBuffer url = new StringBuffer();
//			url.append("http://api.sms1086.com/Api/verifycode.aspx?");
			url.append(OverParameterUtil.url);
//			url.append("username=17550898930");
			url.append("username="+OverParameterUtil.name);
			url.append("&password=" + password);
			url.append("&content=" + content);
			url.append("&mobiles=" + phone);
			url.append("&timestamp=" + timestamp);

			String respone = HttpTemplateUtil.doGet(url.toString(), "gb2312");
			String[] split = respone.split("=");
			String result = split[1].split("&")[0];
			String balance = split[3].split("&")[0];

			if (result.equals("0")) {
				RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
				StringBuffer buffer = new StringBuffer();
				buffer.append(phone);
				buffer.append("vCode");
				boolean set = redisUtil.set(buffer.toString(), vCode, OverParameterUtil.msgTimeOut);
				System.out.println("验证码" + vCode);
				return set;
			}
			System.out.println("短信平台返回码"+result);
			System.out.println("短信平台条数剩余"+balance);
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	
}
